<template>
  <div class="forgot-password-page">
    <div class="form-container">
      <div class="form-header">
        <h2>忘记密码</h2>
        <p>请输入您的用户名，我们将向关联邮箱发送验证码</p>
      </div>

      <el-steps :active="currentStep" finish-status="success" simple>
        <el-step title="验证身份"></el-step>
        <el-step title="重置密码"></el-step>
        <el-step title="完成"></el-step>
      </el-steps>

      <!-- 步骤1: 输入用户名并获取验证码 -->
      <div v-if="currentStep === 0">
        <div class="form-group">
          <el-input
            v-model="username"
            placeholder="请输入用户名"
            prefix-icon="User"
            :disabled="loading"
          />
        </div>
        <div class="form-group verification-code">
          <el-input
            v-model="verificationCode"
            placeholder="请输入验证码"
            prefix-icon="Key"
            :disabled="loading"
          />
          <el-button 
            :disabled="cooldown > 0 || !username || loading" 
            @click="sendVerificationCode"
          >
            {{ cooldown > 0 ? `${cooldown}秒后重试` : '获取验证码' }}
          </el-button>
        </div>
        <el-button
          type="primary"
          class="submit-btn"
          :loading="loading"
          :disabled="!username || !verificationCode"
          @click="verifyCode"
        >
          下一步
        </el-button>
      </div>

      <!-- 步骤2: 设置新密码 -->
      <div v-if="currentStep === 1">
        <div class="form-group">
          <el-input
            v-model="newPassword"
            type="password"
            placeholder="请输入新密码"
            prefix-icon="Lock"
            show-password
            :disabled="loading"
          />
        </div>
        <div class="form-group">
          <el-input
            v-model="confirmPassword"
            type="password"
            placeholder="请确认新密码"
            prefix-icon="Lock"
            show-password
            :disabled="loading"
          />
        </div>
        <el-button
          type="primary"
          class="submit-btn"
          :loading="loading"
          :disabled="!newPassword || !confirmPassword"
          @click="resetPassword"
        >
          重置密码
        </el-button>
      </div>

      <!-- 步骤3: 完成 -->
      <div v-if="currentStep === 2" class="success-container">
        <el-icon class="success-icon"><Check /></el-icon>
        <h3>密码重置成功</h3>
        <p>您已成功重置密码，现在可以使用新密码登录</p>
        <el-button
          type="primary"
          class="submit-btn"
          @click="goToLogin"
        >
          返回登录
        </el-button>
      </div>

      <div class="form-footer">
        <router-link to="/login" class="back-to-login">返回登录</router-link>
      </div>
    </div>
  </div>
</template>

<script setup>
import { ref } from 'vue';
import { useRouter } from 'vue-router';
import { ElMessage } from 'element-plus';
import { User, Lock, Key, Check } from '@element-plus/icons-vue';
import { sendResetCode, verifyResetCode, resetPassword as resetPasswordApi } from '@/api/user';

const router = useRouter();
const username = ref('');
const verificationCode = ref('');
const newPassword = ref('');
const confirmPassword = ref('');
const loading = ref(false);
const currentStep = ref(0);
const cooldown = ref(0);
const token = ref(''); // 存储验证通过后的令牌

// 发送验证码
const sendVerificationCode = async () => {
  if (!username.value) {
    ElMessage.warning('请输入用户名');
    return;
  }

  try {
    loading.value = true;
    const { data } = await sendResetCode({ username: username.value });
    console.log('发送验证码响应数据:', data);
    if (data.code === 200) {
      ElMessage.success('验证码已发送到您的邮箱');
      // 设置冷却时间
      cooldown.value = 60;
      const timer = setInterval(() => {
        cooldown.value--;
        if (cooldown.value <= 0) {
          clearInterval(timer);
        }
      }, 1000);
    } else {
      ElMessage.error(data.message || '发送验证码失败');
    }
  } catch (error) {
    console.error('发送验证码失败:', error);
    ElMessage.error('请求失败，请检查网络连接');
  } finally {
    loading.value = false;
  }
};

// 验证验证码
const verifyCode = async () => {
  if (!username.value || !verificationCode.value) {
    ElMessage.warning('请输入用户名和验证码');
    return;
  }

  try {
    loading.value = true;
    const { data } = await verifyResetCode({
      username: username.value,
      code: verificationCode.value
    });
    console.log('验证响应数据:', data);
    if (data.code === 200) {
      token.value = data.data; // 保存验证成功的令牌
      currentStep.value = 1; // 进入下一步
      ElMessage.success('验证成功');
    } else {
      ElMessage.error(data.message || '验证码错误');
    }
  } catch (error) {
    console.error('验证失败:', error);
    ElMessage.error('请求失败，请检查网络连接');
  } finally {
    loading.value = false;
  }
};

// 重置密码
const resetPassword = async () => {
  if (!newPassword.value || !confirmPassword.value) {
    ElMessage.warning('请输入新密码');
    return;
  }

  if (newPassword.value !== confirmPassword.value) {
    ElMessage.warning('两次输入的密码不一致');
    return;
  }

  if (newPassword.value.length < 6) {
    ElMessage.warning('密码长度不能少于6位');
    return;
  }

  try {
    loading.value = true;
    const { data } = await resetPasswordApi({
      username: username.value,
      newPassword: newPassword.value,
      token: token.value
    });
    
    if (data.code === 200) {
      currentStep.value = 2; // 进入完成步骤
      ElMessage.success('密码重置成功');
    } else {
      ElMessage.error(data.message || '密码重置失败');
    }
  } catch (error) {
    console.error('密码重置失败:', error);
    ElMessage.error('请求失败，请检查网络连接');
  } finally {
    loading.value = false;
  }
};

// 返回登录页
const goToLogin = () => {
  router.push('/login');
};
</script>

<style scoped>
.forgot-password-page {
  min-height: 100vh;
  display: flex;
  align-items: center;
  justify-content: center;
  background: linear-gradient(135deg, #1890ff 0%, #1d39c4 100%);
  padding: 20px;
}

.form-container {
  width: 450px;
  max-width: 90%;
  background: #fff;
  border-radius: 16px;
  box-shadow: 0 8px 24px rgba(0, 0, 0, 0.1);
  padding: 40px;
}

.form-header {
  text-align: center;
  margin-bottom: 30px;
}

.form-header h2 {
  font-size: 24px;
  color: #333;
  margin-bottom: 10px;
}

.form-header p {
  color: #666;
  font-size: 14px;
}

.form-group {
  margin-bottom: 24px;
}

.form-group :deep(.el-input__wrapper) {
  padding: 12px;
  box-shadow: 0 0 0 1px #dcdfe6;
}

.form-group :deep(.el-input__wrapper.is-focus) {
  box-shadow: 0 0 0 1px #1890ff;
}

.verification-code {
  display: flex;
  gap: 10px;
}

.verification-code .el-input {
  flex: 1;
}

.submit-btn {
  width: 100%;
  padding: 12px;
  font-size: 16px;
  margin-top: 10px;
  margin-bottom: 24px;
}

.form-footer {
  text-align: center;
  margin-top: 20px;
}

.back-to-login {
  color: #1890ff;
  text-decoration: none;
}

.back-to-login:hover {
  color: #40a9ff;
}

.success-container {
  text-align: center;
  padding: 20px;
}

.success-icon {
  font-size: 60px;
  color: #52c41a;
  background: #f6ffed;
  border-radius: 50%;
  padding: 10px;
  margin-bottom: 20px;
}

.el-steps {
  margin: 20px 0 30px;
}
</style>